$(document).ready(function () {


    layui.use(function () {

        var layer = layui.layer;

        var laydate = layui.laydate;

        // 年选择器

        laydate.render({

            elem: '#year-change',
            value: new Date().getFullYear(),
            type: 'year',
            disabledDate: function (date, type) {
                return date.getTime() > Date.now();
            },
            done: function (value, date, endDate) {
                curYear = value;
                initMonth()
            }

        });

        initSubMenu();
        initMonth()

    });
})
var params = {};//查询条件参数
var curYear = new Date().getFullYear();//当前选择年份



const monthMap = {
    1: '一月',
    2: '二月',
    3: '三月',
    4: '四月',
    5: '五月',
    6: '六月',
    7: '七月',
    8: '八月',
    9: '九月',
    10: '十月',
    11: '十一月',
    12: '十二月'
}

function

    initMonth() {



    new AjaxChain()
        .setUrl('/pwork/talk/list')
        .setData({
            year: curYear
        })
        .then(data => {


            var str = '';

            for (let index = 1; index < 13; index++) {

                var temp = data.filter(item => item.month == index);

                var moreStr = temp.length < 5 ? (temp.length == 0 ? `<div style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;color: #3e5d68;font-size: 0.16rem;">暂无文件</div>` : '') :
                    `<div class="item-list" style="cursor: pointer;" onclick=showMore(${index})>
                                    <div>
                                        <img src="../static/img/more.png" alt="">
                                        <span>查看更多...</span>
                                    </div>
                                    <div class="calendar-download">
                                        <i class="layui-icon layui-icon-triangle-r"></i>
                                    </div>
                                </div>`



                str = str + `<div class="calendar-item palette">
                            <div id="stats">
                                <img src="../static/img/calendar.png" alt="">
                                <span>${monthMap[index]}</span>
                                <i class="layui-icon layui-icon-upload-drag calendar-upload" onclick=upLoadFile(${index}) title="上传文件"></i>
                            </div>
                            <div class="item-card">
                            ${temp.slice(0, 4).reduce((x, y, i) => {
                    return x +
                        `
                                <div class="item-list">
                                    <div>
                                        <img src="../static/img/file.png" alt="">
                                        <span title="${y.fileName}">${y.fileName}</span>
                                    </div>
                                    <div class="calendar-download">
                                        <a href="/images/${y.filePath}" download="/images/${y.filePath}"><i class="layui-icon layui-icon-download-circle"></i></a><i class="layui-icon layui-icon-close" onclick=delFile("${y.id}")></i>
                                    </div>
                                </div>
                                `
                }, '') + moreStr}

                            </div>
                        </div>`

            }

            $('#calendar').empty().append(

                str
            )

        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();

}


// 删除文件
function delFile(id,month) {

    layer.confirm('确定删除该文件吗？', { icon: 3 }, function () {

        new AjaxChain()
            .setUrl('/pwork/talk/delete')
            .setData({ id: id })
            .then(data => {
                layer.msg('删除成功', { icon: 1, time: 1500 });


                if(month){
                    queryTable(month)
                }
                initMonth();

            })
            .catch(err => {
                console.error('请求异常:', err);
            })
            .send();
    })

}


// 上传文件框
var drawer = null;
function upLoadFile(month) {


    drawer = layer.open({
        type: 1, // page 层类型
        area: ['25%', '30%'],
        title: '文件上传',
        shade: 0.6, // 遮罩透明度
        shadeClose: true, // 点击遮罩区域，关闭弹层
        maxmin: false, // 允许全屏最小化
        anim: 0, // 0-6 的动画形式，-1 不开启
        content: `<div class="upload-container">
		<form class="layui-form" style="display: grid;">
			<label for="arquivo">选择一个文件,文件大小不超过20M:</label>
			<input class="inpdddut" name="file" id="arquivo" type="file">
			<input value="开始上传" lay-filter="save" class="layui-btn inpdddut1" lay-submit >
		</form>
	</div>`
    });

    layui.form.on('submit(save)', function (data) {//监听查询提交
        const formData = new FormData();
        const file = document.getElementById('arquivo').files[0];

        if (file) {

            formData.append('file', file);
            formData.append('type', 1);
            formData.append('year', curYear);
            formData.append('month', month);

            ajaxUploadFile('/pwork/talk/save', upLoadCallBack, formData)
            function upLoadCallBack(res) {
                if (res.message == "OK") {
                    layer.close(drawer);
                    layer.msg('上传成功', { icon: 1, time: 2000 });
                    initMonth()
                } else {
                    layer.msg('上传失败', { icon: 2, time: 2000 });
                }
            }



        } else {
            layer.msg('请选择文件')
        }



        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
}



// 查看更多

function showMore(month) {


    layer.open({
        type: 1, // page 层类型
        area: ['50%', '70%'],
        title: monthMap[month] + '文件列表',
        shade: 0.6, // 遮罩透明度
        shadeClose: true, // 点击遮罩区域，关闭弹层
        maxmin: false, // 允许全屏最小化
        anim: 0, // 0-6 的动画形式，-1 不开启
        content: `<div style="width: 100%;height: 100%;display: flex;"><table id="table" lay-filter="table" style="width: 100%;height: 100%;"></table></div>`,
        success: function () {
            queryTable(month)
        }
    });

}



// 查询表格数据
queryTable = (month) => {
    layui.use('table', function () {

        var table = layui.table;
        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/pwork/talk/list/page"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: {
                pageSize: 10,
                year: curYear,
                month: month,
            }
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[ //标题栏
                { field: 'fileName', title: '文件名称', align: "center" }
                , {
                    field: 'year', title: '所属年月', align: "center",
                    templet: function (d) {
                        return d.year+'年'+monthMap[d.month]
                    },
                }
                , {
                    flex: 'right',
                    title: '操作',
                    align: 'center',
                    width: 200,
                    templet: function (d) {
                        return `<div class="table-tool">
                                    <div class="table-edit layui-btn">
                                    <a href="/images/${d.filePath}" download="/images/${d.filePath}">
                                        <img src="../static/img/download.png">下载
                                    </a>
                                    </div>
                                
                                <div onclick=delFile("${d.id}",${month}) class="table-del layui-btn">
                                  <img src="../static/img/del.png">删除
                                </div>
                              </div>`;
                    },
                },

            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('#table').height() / 20);
            },

        });

    });
}
